module;

#include <boost/mysql.hpp>
#include <boost/mysql/pfr.hpp>

export module DataBaseTest;

import std;

using namespace boost;

asio::io_context ioc;
mysql::any_connection conn(ioc);
void connect() {
	std::string serverIp = "192.144.214.228";
	std::string username = "LaoZuTest";
	std::string password = "LaoZuCIC-Sen123";
	std::string database = "laozutest";

	mysql::connect_params params;
	params.server_address = mysql::host_and_port(serverIp);
	params.username = username;
	params.password = password;
	params.database = database;

	std::clog << "Connecting to MySQL server...\n";
	try {
		conn.connect(params);
	}
	catch (std::exception& e) {
		std::cerr << std::format("Error connecting to MySQL server: {}\n", e.what());
		throw std::runtime_error("MySQL Error");
	}
	std::clog << "Successfully connected to MySQL server.\n";
}
std::string createTableTest = R"(
	CREATE TABLE IF NOT EXISTS Test (
		id VARCHAR(20) PRIMARY KEY,
		name VARCHAR(20),
		status VARCHAR(20)
	)
)";

struct Test {
	std::string id;
	std::optional<std::string> name;
	std::optional<std::string> status;
};
void insertTestData(const Test& test) {
	constexpr auto insertSql = R"(
		INSERT INTO Test (id, name, status) VALUES ({}, {}, {})
	)";
	auto insertQuery = mysql::with_params(insertSql, test.id, test.name, test.status);
	try {
		mysql::results results;
		conn.execute(insertQuery, results);
		std::clog << "Data inserted successfully.\n";
	}
	catch (const std::exception& e) {
		std::cerr << std::format("Error inserting data: {}\n", e.what());
	}
}
void getTestData(std::string_view id) {
	constexpr auto selectSql = R"(
		SELECT id, name, status FROM Test WHERE id = {}
	)";
	auto selectQuery = mysql::with_params(selectSql, id);
	mysql::static_results<mysql::pfr_by_name<Test>> results;
	try {
		conn.execute(selectQuery, results);
		if (results.rows().empty()) {
			std::clog << "No data found for ID: " << id << "\n";
		}
		else {
			std::clog << "Data found for ID: " << id << "\n";
			const Test& test = results.rows().front();
			std::clog << "Data for ID " << id << ": "
				<< "Name: " << test.name.value() << ", "
				<< "Status: " << test.status.value() << "\n";
		}
	}
	catch (const std::exception& e) {
		std::cerr << std::format("Error fetching data: {}\n", e.what());
	}
}
int main() {
	mysql::results results_normal;
	try {
		connect();
		conn.execute(createTableTest, results_normal);
	}
	catch (std::exception& e) {
		std::cerr << e.what() << std::endl;
	}
	insertTestData({ "3232", "5353tyyg", "ygfefd" });
	getTestData("111");
}